package com.cike.algorithm;

public class BubbleSort {
    public static void main(String[] args) {
        int[] a = {1,32,4,43,5,32,5,234,52,345,2,345,2,41,3,243,6243,62,777,62,46,45,63,4,234};
        int[] bubbleRes = bubble(a);

        for (int i = 0; i < bubbleRes.length - 1; i++) {
            System.out.printf(bubbleRes[i] + "\t");
        }

    }


    public static int[] bubble(int[] arr){

        if (arr.length == 0) {
            return arr;
        }

        int lastExchangeIndex = 0;
        int sortBorder = arr.length - 1;

        for (int i = 0; i < arr.length - 1; i++) {
            boolean isSorted = true;
            for (int j = 0; j < sortBorder; j++) {
                if (arr[j + 1] < arr[j]) {
                    int temp = arr[j + 1];
                    arr[j + 1] = arr[j];
                    arr[j] = temp;

                    isSorted = false;
                    lastExchangeIndex = j;
                }
            }
            sortBorder = lastExchangeIndex;
            if (isSorted) {
                break;
            }
        }
        return arr;
    }


}
